package cn.legend.travel.ask.service.impl;

import cn.legend.travel.ask.dao.persist.repository.AnswerRepository;
import cn.legend.travel.ask.dao.persist.repository.AsksRepository;
import cn.legend.travel.ask.pojo.entity.Answer;
import cn.legend.travel.ask.pojo.entity.Ask;
import cn.legend.travel.ask.pojo.entity.UserCollection;
import cn.legend.travel.ask.pojo.param.AddNewAsksParam;
import cn.legend.travel.ask.pojo.vo.*;
import cn.legend.travel.common.enumerator.ServiceCode;
import cn.legend.travel.common.exception.ServiceException;
import cn.legend.travel.common.pojo.authentication.CurrentPrincipal;
import cn.legend.travel.common.pojo.vo.PageData;
import cn.legend.travel.common.util.DataTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import cn.legend.travel.ask.service.AskService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Slf4j
@Service
public class AskServiceImpl implements AskService {
    @Autowired
    private AsksRepository asksRepository;
    @Autowired
    private AnswerRepository answerRepository;
    @Value("${travel.dao.default-query-page-size}")
    private Integer pageSize;
    @Override
    public List<AskStandardVO> getAsks(Integer pageNum,Integer type,CurrentPrincipal principal) {
        String sort = type == 1  ? "gmt_create" : "like_count";
        List<AskVo> asks = asksRepository.getAsks(pageNum, pageSize, sort);
        List<AskStandardVO> list = new ArrayList<>();
        for (AskVo a : asks) {
            if (a.getAnswerFavoriteId() == null){
                AskStandardVO askVO = new AskStandardVO();
                BeanUtils.copyProperties(a,askVO);
                list.add(askVO);
            }else {
                AskStandardVO askVO = new AskStandardVO();
                AnswerStandardVO bestAsk = principal == null? answerRepository.getBestAsk(a.getAnswerFavoriteId())
                : answerRepository.getBestAsk(a.getAnswerFavoriteId(),principal);
                BeanUtils.copyProperties(bestAsk,askVO);
                askVO.setViewCount(a.getViewCount());
                askVO.setId(a.getId());
                askVO.setTitle(a.getTitle());
                askVO.setLikeCount(a.getLikeCount());
                list.add(askVO);
            }
        }
        return list;
    }

    @Override
    public void addAsks(AddNewAsksParam asksParam,CurrentPrincipal currentPrincipal) {
        asksParam.setUserId(currentPrincipal.getId());
        int i = asksRepository.addAsks(asksParam);
        if (i!=1){
            throw new ServiceException(ServiceCode.ERROR_UNKNOWN,"服务器忙，请再试一次");
        }
    }

    @Override
    public List<UserSortVo> getBestUsers(Integer time,Integer type) {
        Date localDateTime;
        String category;
        switch (time){
            case 0 :  localDateTime = DataTime.getTimesMorning();break;
            case 1 :  localDateTime = DataTime.getTimesWeekMorning();break;
            default:  localDateTime = DataTime.getTimesMonthMorning();break;
        }
        switch (type){
            case 0 : category = "like_count";break;
            case 1 : category = "total";break;
            default: category = "is_recommendation";break;
        }
        return asksRepository.getBestUsers(localDateTime,category);
    }

    @Override
    public PageData<AnswerVo> getAnswers(Long questionId,Integer pageNum) {
        return asksRepository.getAnswers(questionId,pageNum,pageSize);
    }

    @Override
    public PageData<AsksSearchVo> search(String keyword, Integer page) {
        return null;
    }

    @Override
    public void addLikes(Long questionId,CurrentPrincipal currentPrincipal) {
        //TODO 和user相关的东西
        Long id = currentPrincipal.getId();
        UserCollection userCollection = asksRepository.getCollection(questionId,id,"asks");
        if (userCollection != null){
            throw new ServiceException(ServiceCode.ERROR_CONFLICT,"该用户已点赞，请勿重复点赞");
        }
        userCollection = new UserCollection();
        userCollection.setRate(0);
        userCollection.setObjId(questionId);
        userCollection.setType("asks");
        userCollection.setUserId(id);
        int d =asksRepository.insert(userCollection);
        if (d !=1){
            throw new ServiceException(ServiceCode.ERROR_UNKNOWN,"服务器出现异常，请稍后再试");
        }
        int i = answerRepository.addLikes(questionId);
        if (i!=1){
            throw new ServiceException(ServiceCode.ERROR_UNKNOWN,"服务器出现异常，请稍后再试");
        }
    }

    @Override
    public void cancelLikes(Long questionId, CurrentPrincipal currentPrincipal) {
        //TODO 和user相关的东西
        Long id = currentPrincipal.getId();
        UserCollection userCollection = asksRepository.getCollection(questionId,id,"answer");
        if (userCollection == null){
            throw new ServiceException(ServiceCode.ERROR_NOT_FOUND,"已取消请勿重复点赞");
        }
        Answer ask = answerRepository.getAnswer(questionId);
        if (ask ==null){
            throw new ServiceException(ServiceCode.ERROR_UPLOAD_EMPTY,"该回复已经删除，请稍后再试");
        }
        int i =answerRepository.cancelLikes(questionId);
        if (i!=1){
            throw new ServiceException(ServiceCode.ERROR_UPDATE,"服务器忙，请稍后再试");
        }
    }

    @Override
    public void AddViews(Long questionId) {
        Ask ask = asksRepository.getAsk(questionId);
        if (ask ==null){
            throw new ServiceException(ServiceCode.ERROR_UPLOAD_EMPTY,"该回复已经删除，请稍后再试");
        }
        int i = asksRepository.addView(questionId);
        if (i!=1){
            throw new ServiceException(ServiceCode.ERROR_UPDATE,"服务器忙，请稍后再试");
        }
    }

    @Override
    public void report(Long questionId) {
        Ask ask = asksRepository.getAsk(questionId);
        if (ask ==null){
            throw new ServiceException(ServiceCode.ERROR_UPLOAD_EMPTY,"该回复已经删除，请稍后再试");
        }
        int i =asksRepository.report(questionId);
        if (i!=1){
            throw new ServiceException(ServiceCode.ERROR_UPDATE,"服务器忙，请稍后再试");
        }
    }

    @Override
    public List<AskSimple> getByCity(String city) {
        List<AskSimple> list = new ArrayList<>();
        List<AsksCitySimpleVO> byCity = asksRepository.getByCity(city);
        for (AsksCitySimpleVO by : byCity ){
            AskSimple askSimple = new AskSimple();
            AnswerStandardVO bestAsk = answerRepository.getBestAsk(by.getAnswerFavoriteId());
            BeanUtils.copyProperties(by,askSimple);
            askSimple.setAnswerAvatar(bestAsk.getAvatar());
            askSimple.setAnswerUserId(bestAsk.getUserId());
            askSimple.setAnswerUsername(bestAsk.getUsername());
            askSimple.setContent(bestAsk.getContent());
            list.add(askSimple);
        }
        return list;
    }

    @Override
    public Ask getAskById(Long questionId) {
        return asksRepository.getAskById(questionId);
    }
}
